<template>
  <div>
    <!-- 新建批次 -->
    <div v-show="newBatch && !print" class="transactionCommissionNew">
      <el-breadcrumb separator="/" style="font-size:16px;height:30px;">
        <el-breadcrumb-item :to="{ path: '/transactionAndCommission' }">交易及佣金</el-breadcrumb-item>
        <el-breadcrumb-item>新建批次</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="filter">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="城市：">
            <el-select v-model="cityId" placeholder="请选择城市" size="mini" filterable clearable @change="getCityId">
              <el-option
                :label="item.city"
                :value="item.cityId"
                v-for="(item,idx) in cityList"
                :key="idx"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="楼盘：">
            <el-select v-model="devId" placeholder="请选择楼盘" size="mini" filterable clearable>
              <el-option
                :label="item.devName"
                :value="item.devId"
                v-for="(item,idx) in devList"
                :key="idx"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户状态：">
            <el-select v-model="customerStatusId" placeholder='全部' size="mini">
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="(item,idx) in customerStatusList"
                :key="idx"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户姓名：">
            <el-input v-model="customerName" placeholder="请输入客户姓名" size="mini"></el-input>
          </el-form-item>
          <el-form-item label="渠道公司名称：">
            <el-input v-model="companyName" placeholder="请输入渠道公司名称" size="mini"></el-input>
          </el-form-item>
          <el-form-item style="margin-top:-2px;margin-left:10px;">
            <el-button type="primary" @click="checkList" size="mini" id="monitorEnter">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table
        :data="listDataNew"
        border
        style="width: 100%"
        @selection-change="handleSelectionChangeNew"
      >
        <el-table-column align="center" fixed type="selection" width="55"></el-table-column>
        <el-table-column align="center" fixed label="序号" type="index" width="60"></el-table-column>
        <el-table-column align="center" prop="cityName" label="城市" width="150"></el-table-column>
        <el-table-column align="center" prop="customerName" label="客户姓名" width="150"></el-table-column>
        <el-table-column
          align="center"
          prop="customerPhone"
          label="手机号"
          width="150"
          :formatter="initPhone"
        ></el-table-column>
        <el-table-column align="center" prop="devName" label="楼盘名称" width="300"></el-table-column>
        <el-table-column align="center" prop="houseNum" label="房间号" width="200"></el-table-column>
        <el-table-column align="center" prop="houseArea" label="面积" width="120"></el-table-column>
        <el-table-column align="center" prop="nodeName" label="客户状态" width="120"></el-table-column>
        <el-table-column align="center" prop="dealAmount" label="成交价" width="150" :formatter="initMoney"></el-table-column>
        <el-table-column
          align="center"
          prop="devAmount"
          label="房款"
          width="150"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column align="center" prop="packageName" label="套餐名称" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleCheckRule(scope.row)" :disabled="scope.row.packageName?false:true">{{scope.row.packageName}}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="amountTotal"
          label="好生活总收入金额"
          width="180"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="frontAmount"
          label="前佣"
          width="180"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="afterAmount"
          label="后佣"
          width="180"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="awardAmountTotal"
          label="经纪人奖励"
          width="180"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column align="center" prop="awardSource" label="奖励来源" width="180">
          <template slot-scope="scope">
            <span v-show="scope.row.awardSource == 1">开发商-返还款</span>
            <span v-show="scope.row.awardSource == 2">开发商-回款</span>
            <span v-show="scope.row.awardSource == 5">前佣-经纪人分佣</span>
            <span v-show="scope.row.awardSource == 6">后佣-经纪人分佣</span>
            <span v-show="!scope.row.awardSource">-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="brokerAmount" label="渠道佣金" width="180" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="brokerAmountFront" label="渠道前佣" width="180" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="brokerAmountAfter" label="渠道后佣" width="180" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="brokerAwardAmount" label="渠道经纪人奖励" width="180" :formatter="initMoney"></el-table-column>
        <el-table-column align="center" prop="companyName" label="渠道公司" width="180">
          <template slot-scope="scope">
            {{scope.row.companyName?scope.row.companyName:'-'}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="dealTime"
          label="交易时间"
          width="180"
          :formatter="initTime"
        ></el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pageData.pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageData.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="totalSize"
        ></el-pagination>
      </div>
      <div style="text-align:center;margin-top:40px;margin-bottom:30px;">
        <el-button type="primary" @click="handleCancle" size="mini">返回</el-button>
        <el-button type="primary" @click="handleAddBatch(1)" size="mini">添加到批次</el-button>
        <el-button type="primary" @click="handleAddBatch(2)" size="mini">添加到批次到下一步</el-button>
      </div>
    </div>
    <!-- 下一步 -->
    <div v-show="!newBatch && !print" class="transactionCommissionNewNext">
      <div class="top">
        <span class="one">
          <span>城市：</span>
          <span>{{devInfo.cityName}}</span>
        </span>
        <span class="one">
          <span>楼盘：</span>
          <span>{{devInfo.devName}}</span>
        </span>
      </div>
      <div>
        <el-button class="pri" type="primary" size="mini" @click="handlePrint">打印</el-button>
      </div>
      <el-table
        :data="listData"
        border
        style="width: 100%"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" fixed type="selection" width="55"></el-table-column>
        <el-table-column align="center" fixed label="序号" type="index" width="60"></el-table-column>
        <el-table-column align="center" prop="cityName" label="城市" width="150"></el-table-column>
        <el-table-column align="center" prop="customerName" label="客户姓名" width="150"></el-table-column>
        <el-table-column
          align="center"
          prop="customerPhone"
          label="手机号"
          width="150"
          :formatter="initPhone"
        ></el-table-column>
        <el-table-column align="center" prop="devName" label="楼盘名称" width="300"></el-table-column>
        <el-table-column align="center" prop="houseNum" label="房间号" width="200"></el-table-column>
        <el-table-column align="center" prop="houseArea" label="面积" width="120"></el-table-column>
        <el-table-column align="center" prop="nodeName" label="客户状态" width="120"></el-table-column>
        <el-table-column align="center" prop="dealAmount" label="成交价" width="150"></el-table-column>
        <el-table-column
          align="center"
          prop="devAmount"
          label="房款"
          width="150"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column align="center" prop="packageName" label="套餐名称" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleCheckRule(scope.row)" :disabled="scope.row.packageName?false:true">{{scope.row.packageName}}</el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="amountTotal"
          label="好生活总收入金额"
          width="180"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="frontAmount"
          label="前佣"
          width="180"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="afterAmount"
          label="后佣"
          width="180"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="awardAmountTotal"
          label="经纪人奖励"
          width="180"
          :formatter="initMoney"
        ></el-table-column>
        <el-table-column align="center" prop="awardSource" label="奖励来源" width="180">
          <template slot-scope="scope">
            <span v-show="scope.row.awardSource == 1">开发商-返还款</span>
            <span v-show="scope.row.awardSource == 2">开发商-回款</span>
            <span v-show="scope.row.awardSource == 5">前佣-经纪人分佣</span>
            <span v-show="scope.row.awardSource == 6">后佣-经纪人分佣</span>
            <span v-show="!scope.row.awardSource">-</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="brokerAmount" label="渠道佣金" width="180"></el-table-column>
        <el-table-column align="center" prop="brokerAmountFront" label="渠道前佣" width="180"></el-table-column>
        <el-table-column align="center" prop="brokerAmountAfter" label="渠道后佣" width="180"></el-table-column>
        <el-table-column align="center" prop="brokerAwardAmount" label="渠道经纪人奖励" width="180"></el-table-column>
        <el-table-column align="center" prop="companyName" label="渠道公司" width="180">
          <template slot-scope="scope">
            {{scope.row.companyName?scope.row.companyName:'-'}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="dealTime"
          label="交易时间"
          width="180"
          :formatter="initTime"
        ></el-table-column>
      </el-table>
      <div class="part">
        <div class="txt">佣金确认表：</div>
        <div class="content">
          <upload :multiple="true" ref="upload4" :fileList="yongjinList" />
        </div>
      </div>
      <div class="btn">
        <el-button type="primary" size="mini" @click="handleReturn">继续添加</el-button>
        <el-button type="primary" size="mini" @click="save(0)">保存</el-button>
        <el-button type="primary" size="mini" @click="save(1)">保存并提交审核</el-button>
      </div>
    </div>
    <orderPrint ref="orderPrint" v-show="print == 'print'" v-on:print="close" />
  </div>
</template>

<script>
import api from "@/api/apiPath";
import util from "@/common/utils";
import upload from "@/components/common/Upload";
import orderPrint from "./orderPrint";
export default {
  name: "transactionCommissionNew",
  components: {
    upload,
    orderPrint
  },
  data() {
    return {
      print: "",
      newBatch: true,
      listData: [],
      yongjinList: [],
      listDataNew: [],
      multipleSelection: [],
      multipleSelectionNew: [],
      multipleSelectionAllNew: [],
      multipleSelectionAll: [],
      cityList: [],
      cityId: "",
      devList: [],
      devId: "",
      customerStatusList: [
        { name: "全部", id: "" },
        { name: "认购", id: "PURCHASE" },
        { name: "草签", id: "INITIAL" },
        { name: "签约", id: "SIGN" },
        { name: "退认购", id: "REFUND_PURCHASE" }
      ],
      customerStatusId: undefined,
      customerName: "",
      companyName: '',
      tempcompanyInfoIdNew: [],
      tempcompanyInfoId: [],
      idKeyNew: "companyInfoId",
      idKey: "companyInfoId",
      totalSize: 0,
      pageData: {
        pageNum: 1,
        pageSize: 10
      },
      devInfo: {},
      id: [],
      yongjinData: {
        pdfarr: [],
        pictures: []
      }
    };
  },
  mounted() {},
  created() {
    this.getCityList()
    this.orderList(this.id)
    window.localStorage.removeItem("tempcompanyInfoIdNew")
    this.getDevList()
  },
  methods: {
    checkList(){
      if(window.localStorage.getItem("tempcompanyInfoIdNew")){
        this.id = window.localStorage.getItem("tempcompanyInfoIdNew").split(",")
      }
      this.pageData.pageNum = 1
      this.orderList(this.id)
    },
    // 查看佣金套餐规则
    handleCheckRule(row){
      let route = this.$router.resolve({path:'/ruleDetail',query:{
        customerFollowId:row.customerFollowId,
      }})
      window.open(route.href,'_blank')
    },
    close(val) {
      this.print = "";
    },
    initPhone(row, column, cellValue, index) {
      return util.formatPhoneNumber(cellValue);
    },
    initMoney(row, column, cellValue, index) {
      return util.formatMoney(cellValue);
    },
    initTime(row, column, cellValue, index) {
      return util.getTimeString(cellValue);
    },
    // 打印
    handlePrint() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择订单"
        });
        return;
      }
      window.sessionStorage.setItem(
        "tal",
        JSON.stringify(this.multipleSelection)
      );
      this.print = "print";
      this.$refs.orderPrint.getDevInfo()
    },
    // 每页条数
    handleSizeChange(val) {
      this.pageData.pageSize = val
      this.orderList(this.id)
    },
    // 下一页
    handleCurrentChange(val) {
      this.orderList(this.id)
    },
    // 订单总列表
    orderList(tempcompanyInfoId) {
      let temId = [];
      if (tempcompanyInfoId == []) {
        temId = [];
      } else {
        temId = tempcompanyInfoId
      }
      this.axios
        .post(api.getBrokerageCompanyInfoList, {
          pageNum: this.pageData.pageNum,
          pageSize: this.pageData.pageSize,
          devId: this.devId,
          cityId: this.cityId,
          customerName: this.customerName,
          companyName: this.companyName,
          followType: this.customerStatusId,
          tempcompanyInfoId: temId
        })
        .then(res => {
          if (res.data.code == 200) {
            this.totalSize = res.data.data.total;
            this.listDataNew = res.data.data.rows;
          }
        });
    },

    toggleSelection(rows) {
      console.log(rows);

      if (rows) {
        this.$nextTick(()=>{
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row,true)
          })
        })
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 新建批次-多选
    handleSelectionChangeNew(val) {
      this.multipleSelectionNew = val;
      setTimeout(() => {
        this.changePageCoreRecordDataNew();
      }, 300);
    },
    // 下一步-多选
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val;
      // setTimeout(() => {
      //   this.changePageCoreRecordData();
      // }, 300);
    },
    // 城市列表
    getCityList() {
      this.axios.post(api.CITYLIST).then(res => {
        if (res.data.code == 200) {
          this.cityList = res.data.data.cityList;
        }
      });
    },
    getCityId(val){
      this.getDevList(val)
      this.devId = ''
    },
    // 楼盘列表
    getDevList(val) {
      this.axios.post(api.queryAllDevList, {
        cityId:val
      }).then(res => {
        if (res.data.code == 200) {
          this.devList = res.data.data;
        }
      });
    },
    // 添加到批次
    handleAddBatch(val) {
      let listDataLength = this.listData.length
      this.listData = this.listData.concat(this.multipleSelectionNew)
      console.log(this.listData);

      if (window.localStorage.getItem("tempcompanyInfoIdNew")) {
        let tempcompanyInfoIdNew = window.localStorage
          .getItem("tempcompanyInfoIdNew")
          .split(",")
        window.localStorage.setItem(
          "tempcompanyInfoIdNew",
          tempcompanyInfoIdNew.concat(this.tempcompanyInfoIdNew)
        )
      } else {
        window.localStorage.setItem(
          "tempcompanyInfoIdNew",
          this.tempcompanyInfoIdNew
        )
      }
      if(val == 1){
        if(this.tempcompanyInfoIdNew.length == 0){
          this.$message({
            type: "warning",
            message: "至少选择一条订单并添加到批次"
          })
          return
        }
        // this.checkDev(this.id)
        // 被选中的楼盘id
        let devId = []
        this.listData.forEach(item=>{
          devId.push(item.devId)
        })
        if(Array.from(new Set(devId)).length!=1){
          this.$message.error('请选择同一楼盘的订单')
          this.listData = this.listData.splice(0,listDataLength)
          console.log(this.listData)
          return
        }
        this.id = window.localStorage.getItem("tempcompanyInfoIdNew").split(",")
        this.orderList(this.id)
        this.$message({
          type:'success',
          message:'成功添加'+this.tempcompanyInfoIdNew.length+'条信息到批次'
        })
      }else if (val == 2){
        if(this.tempcompanyInfoIdNew.length == 0 ){
          if(this.listData.length == 0){
            this.$message({
              type: "warning",
              message: "至少选择一条订单并添加到批次"
            })
            return
          }
        }else{
          // 被选中的楼盘id
          let devId = []
          this.listData.forEach(item=>{
            devId.push(item.devId)
          })
          if(Array.from(new Set(devId)).length!=1){
            this.$message.error('请选择同一楼盘的订单')
            this.listData = this.listData.splice(0,listDataLength)
            return
          }
          this.id = window.localStorage.getItem("tempcompanyInfoIdNew").split(",");
          console.log(window.localStorage.getItem("tempcompanyInfoIdNew").split(","));

          console.log(this.id)
          this.orderList(this.id)
          this.$message({
            type:'success',
            message:'成功添加'+this.tempcompanyInfoIdNew.length+'条信息到批次'
          })
        }
        this.devInfo = this.listData[0];
        this.newBatch = !this.newBatch;
      }
      this.toggleSelection(this.listData)
    },
    // 返回
    handleCancle() {
      this.$router.push("/transactionAndCommission");
    },
    // 下一步页面
    // 继续添加
    handleReturn() {
      this.newBatch = !this.newBatch;
    },
    // 保存
    save(val) {
      if (this.multipleSelection.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择订单"
        });
        return;
      } else {
        this.multipleSelection.forEach((item, index) => {
          item.dataIndex = index + 1;
        });
      }
      Promise.all([
        this.$refs.upload4.submit()
      ]).then(res => {
        console.log(res)
        if (res[0].length < 1) {
          this.$message({
            message: "佣金确认表不能为空",
            type: "warning"
          });
          return;
        }
        // 佣金确认表
        this.yongjinData.pdfarr = [];
        this.yongjinData.pictures = [];
        res[0].forEach(item => {
          let suffix = item.substring(item.lastIndexOf(".") + 1, item.length);
          if (suffix == "pdf") {
            this.yongjinData.pdfarr.push({
              name: item.substring(item.lastIndexOf("/") + 1, item.length),
              url: item
            });
          } else {
            this.yongjinData.pictures.push({
              name: item.substring(item.lastIndexOf("/") + 1, item.length),
              url: item
            });
          }
        });
        this.axios
          .post(api.save, {
            auditStatus: val,
            data: this.multipleSelection,
            pictureAddress: this.yongjinData // 佣金确认表
          })
          .then(res => {
            if (res.data.code == 200) {
              this.$router.push({ path: "/transactionAndCommission" });
            }
          });
      });
    },

    // 记忆选择核心方法
    changePageCoreRecordDataNew() {
      // 标识当前行的唯一键的名称
      let idKeyNew = this.idKeyNew;
      let that = this;
      this.multipleSelectionAllNew = this.multipleSelectionNew;
      // 总选择里面的key集合
      let selectAllIds = [];
      this.multipleSelectionAllNew.forEach(row => {
        selectAllIds.push(row[idKeyNew]);
      });
      // console.log("总选择的key", selectAllIds);
      this.tempcompanyInfoIdNew = [];
      // 获取当前页选中的id
      this.multipleSelectionNew.forEach(row => {
        this.tempcompanyInfoIdNew.push(row[idKeyNew]);
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKeyNew]) < 0) {
          that.multipleSelectionAllNew.push(row);
        }
      });
      // console.log("当前也的选中id", this.tempcompanyInfoIdNew);
      let noSelectIds = [];
      // 得到当前页没有选中的id
      this.listDataNew.forEach(row => {
        if (this.tempcompanyInfoIdNew.indexOf(row[idKeyNew]) < 0) {
          noSelectIds.push(row[idKeyNew]);
        }
      });
      noSelectIds.forEach(id => {
        if (selectAllIds.indexOf(id) >= 0) {
          for (let i = 0; i < that.multipleSelectionAllNew.length; i++) {
            if (that.multipleSelectionAllNew[i][idKeyNew] == id) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.multipleSelectionAllNew.splice(i, 1);
              break;
            }
          }
        }
      });
    },
    changePageCoreRecordData() {
      // 标识当前行的唯一键的名称
      let idKey = this.idKey;
      let that = this;
      this.multipleSelectionAll = this.multipleSelection;
      // 总选择里面的key集合
      let selectAllIds = [];
      this.multipleSelectionAll.forEach(row => {
        selectAllIds.push(row[idKey]);
      });
      // console.log("总选择的key", selectAllIds);
      this.tempcompanyInfoId = [];
      // 获取当前页选中的id
      this.multipleSelection.forEach(row => {
        this.tempcompanyInfoId.push(row[idKey]);
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKey]) < 0) {
          that.multipleSelectionAll.push(row);
        }
      });
      // console.log("当前也的选中id", this.tempcompanyInfoId);
      let noSelectIds = [];
      // 得到当前页没有选中的id
      this.listData.forEach(row => {
        if (this.tempcompanyInfoId.indexOf(row[idKey]) < 0) {
          noSelectIds.push(row[idKey]);
        }
      });
      noSelectIds.forEach(id => {
        if (selectAllIds.indexOf(id) >= 0) {
          for (let i = 0; i < that.multipleSelectionAll.length; i++) {
            if (that.multipleSelectionAll[i][idKey] == id) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.multipleSelectionAll.splice(i, 1);
              break;
            }
          }
        }
      });
    }
  },
  computed: {}
};
</script>
<style lang="stylus" scoped>
.transactionCommissionNew {
  .block {
    margin-top: 15px;
  }

  .packageName {
    color: #409EFF !important;
  }
}

.transactionCommissionNewNext {
  .top {
    margin-bottom: 15px;
    font-size: 14px;
    color: #909399;
  }

  .one {
    margin-right: 50px;
  }

  .pri {
    float: right;
    margin-bottom: 15px;
  }

  .part {
    margin-top: 30px;
    display: flex;
    font-size: 14px;
    color: #909399;
  }

  .txt {
    width: 200px;
  }

  .btn {
    margin-top: 30px;
    padding-left: 200px;
  }

  .packageName {
    color: #409EFF !important;
  }
}
</style>
